package com.lagou.controller;

import com.lagou.entity.PayOrder;
import com.lagou.entity.PayOrderRecord;
import com.lagou.entity.SmsVo;
import com.lagou.entity.UserCourseOrder;
import com.lagou.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @GetMapping("saveOrder")
    public String saveOrder(String orderNo,String user_id , String course_id,String activity_course_id,String source_type,Double price) {
        // 保存支付订单
        orderService.saveOrder(orderNo, user_id, course_id, activity_course_id, source_type);
        // 保存订单的记录日志
        PayOrderRecord record = new PayOrderRecord();
        record.setOrder_no(orderNo);
        record.setType("CREATE"); //代表保存订单
        record.setFrom_status("0");
        record.setTo_status("1");
        record.setPaid_amount(price);
        record.setCreated_by(user_id);
        record.setCreated_at(new Date());
        System.out.println("创建订单记录 = " + orderNo);
        orderService.saveOrderRecord(record);




        return orderNo;
    }

    @GetMapping("updateOrder")
    public Integer updateOrder(HttpServletRequest request,String orderNo , Integer status, String user_id, String course_id, String course_name, Double price, String phone) {
        System.out.println(phone+"22");
        System.out.println("订单编号 = " + orderNo);
        System.out.println("状态编码 = " + status);
        Integer integer = orderService.updateOrder(orderNo, status);
        System.out.println("订单更新 = " + integer);
        RedisSerializer rs = new StringRedisSerializer();
        redisTemplate.setKeySerializer(rs);
        redisTemplate.delete("myCourses");

        if(integer == 1){
            // 记录订单支付的详情
            PayOrder po = new PayOrder();
            po.setOrder_no(orderNo);
            po.setUser_id(user_id);
            po.setProduct_id(course_id);
            po.setProduct_name(course_name);
            po.setAmount(price);
            po.setCount(1);
            po.setCurrency("cny");
            po.setChannel("weChat");
            po.setStatus(2); //2，代表支付成功
            po.setOrder_type(1);
            po.setSource(3);
            //po.setClient_ip("192.168.1.1"); // 自行解决：获取客户端ip
            //解决方式如下：
            System.out.println(request.getRemoteAddr()+":"+request.getRemotePort());
            String ip = request.getRemoteAddr();
            System.out.println("0:0:0:0:0:0:0:1");
            System.out.println(request.getRemoteAddr());
            System.out.println("0:0:0:0:0:0:0:1".equals(request.getRemoteAddr()));
            if("0:0:0:0:0:0:0:1".equals(request.getRemoteAddr())){
                ip = "127.0.0.1";
            }
            po.setClient_ip(ip); //得到ip，就不得端口了，因为字段的长度有限（sql设置的）
            po.setCreated_time(new Date());
            po.setUpdated_time(new Date());

            orderService.saveOrderInfo(po);

            // 记录支付操作的日志
            PayOrderRecord record = new PayOrderRecord();
            record.setOrder_no(orderNo);
            record.setType("PAY"); //代表支付
            record.setFrom_status("1"); //从0，变成1
            record.setTo_status("2"); //从1，变成2
            //很明显，保存订单的同时，若我们支付了，那么该订单会出现成功的记录
            record.setPaid_amount(price);
            record.setCreated_by(user_id);
            record.setCreated_at(new Date());
            System.out.println("创建订单记录 = " + orderNo);

            orderService.saveOrderRecord(record);
            System.out.println("88888888");
            System.out.println("88888888");
            // 发送短信成功的通知
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(phone);// 手机号码
            smsVo.setCourseName(course_name);
            System.out.println(smsVo);
            rabbitTemplate.convertAndSend(queue,smsVo);

        }
        System.out.println("88888888");
        return integer;
    }

    @GetMapping("deleteOrder")
    public Integer deleteOrder(String orderno) {

        Integer integer = orderService.deleteOrder(orderno);
        return integer;

    }

    @GetMapping("getOrdersByUserId/{userId}")
    public List<UserCourseOrder> getOrdersByUserId(@PathVariable("userId") String userId) {

        List<UserCourseOrder> ordersByUserId = orderService.getOrdersByUserId(userId);

        return ordersByUserId;

    }

    @GetMapping("getOKOrderCourseIds")
    public List<Object> getOKOrderCourseIds(Integer userid){
        System.out.println("oo:"+userid);
        List<UserCourseOrder> list = orderService.getOKOrderCourseIds(userid);
        List<Object> ids = new ArrayList<>();
        for(UserCourseOrder order : list){
            ids.add( order.getCourseId() );
        }
        return ids;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //导入import org.springframework.beans.factory.annotation.Value;这个
    @Value("${spring.rabbitmq.queue}")
    private String queue;
    // mq的生产端
    @GetMapping("sendMQ")
    public void sendMQ(){
        String msg = "你好啊，mq！";
        rabbitTemplate.convertAndSend(queue,msg);
    }


}